package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.AfterEsTrigger;
import com.ruoyi.common.utils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class EsTriggerAspect {

    // 定义切入点：所有带有@AfterEsTrigger注解的方法
    @AfterReturning(pointcut = "@annotation(afterEsTrigger)", returning = "result")
    public void afterEsTriggered(JoinPoint joinPoint, AfterEsTrigger afterEsTrigger, Object result) {
        // 获取目标类
        Object target = joinPoint.getTarget();
        Class<?> targetClass = target.getClass();

        // 查找类中所有方法，寻找名称包含"Es"的方法
        Method[] methods = targetClass.getDeclaredMethods();
        if (StringUtils.isEmpty(afterEsTrigger.value())) {
            return;
        }
        for (Method method : methods) {
            if (method.getName().equals(afterEsTrigger.value())) {
                try {
                    // 调用匹配的方法
                    method.setAccessible(true);
                    method.invoke(target);
                    break;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
